from django.core.management.base import BaseCommand, CommandError 
from optparse import make_option 
import os 
import sys 

class Command(BaseCommand):
  option_list = BaseCommand.option_list + (
                  make_option('--noreload', action='store_false', dest='use_reloader', default=True, help='Tells Django to NOT use the auto-reloader.'),
                  make_option('--detach', action='store_true', dest='detach', default=False, help='Run the mail server as a daemon'),
                  make_option('--logout', action='store', dest='logout', help='Log file location'),
                  make_option('--logerr', action='store', dest='logerr', help='Error log file location'),
                  make_option('--pidfile', action='store', dest='pidfile', help='PID file location'),
  )
  help = 'Starts a lightweight mail server'
  args = '[optional port number, or ipaddr:port]'

  requires_model_validation = False

  def handle(self, addrport='', *args, **options):
    import django
    import django_smtpd
    from django.utils import translation

    if args:
      raise CommandErrors('Usage is runmailserver %s' % self.args)
    if not addrport:
      addr = ''
      port = '25'
    else:
      try:
        addr, port = addrport.split(':')
      except ValueError:
        addr, port = '', addrport
    if not addr:
      addr = '127.0.0.1'
    if not port.isdigit():
      raise CommandError("%r is not a valid port number" % port)
    
    use_reloader = options.get('use_reloader', True) 
    detach = options.get('detach', False)
    shutdown_message = options.get('shutdown_message', '') 
    quit_command = (sys.platform == 'win32') and 'CTRL-BREAK' or 'CONTROL-C' 

    def inner_run():
      from django.conf import settings 
      print "Validating models..." 
      self.validate(display_num_errors=True) 
      print "\nDjango version %s, using settings %r" % (django.get_version(), settings.SETTINGS_MODULE) 
      print "Mail server is running at %s:%s" % (addr, port) 
      print "Quit the server with %s." % quit_command 

      translation.activate(settings.LANGUAGE_CODE)
      django_smtpd.server.run_basic(django_smtpd.handlers.BasicMessageHandler, addr, int(port))

    if detach:
      daemon_kwargs = {}
      if options.get('logout'):
        daemon_kwargs['out_log'] = options.get('logout')
      if options.get('logerr'):
        daemon_kwargs['err_log'] = options.get('logerr')
      if options.get('pidfile'):
        daemon_kwargs['pidfile'] = pidfile =options.get('pidfile')
      
      from django.utils.daemonize import become_daemon
      become_daemon(our_home_dir=os.getcwd(), **daemon_kwargs)

      if options.get("pidfile"):
        fp = open(options.get("pidfile"), "w")
        fp.write("%d\n" % os.getpid())
        fp.close()


    if use_reloader:
      from django.utils import autoreload
      autoreload.main(inner_run)
    else:
      inner_run()

def findpid(pidfile):
    f = open(pidfile)
    p = f.read()
    f.close()
    return int(p)

